
package com.doform.android.xianggucheng.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.bean.CategoryQueryBean;
import com.doform.android.xianggucheng.bean.GuidBean;
import com.doform.android.xianggucheng.bean.IPickerAddressBean;
import com.doform.android.xianggucheng.bean.ImageBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqAddVendorBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqImage;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryCategory;
import com.doform.android.xianggucheng.popwindow.PopCategory;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.BitMapUtil;
import com.doform.android.xianggucheng.utils.GetJsonDataUtil;
import com.doform.android.xianggucheng.utils.RexUtils;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DIYScrollView;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.google.gson.Gson;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;

/**
 * Created by Administrator on 2017/5/12.
 */

public class NewVendorActivity extends BaseTitleActivity {

    @BindView(R.id.tv_address)
    TextView mAddress;

    @BindView(R.id.et_name)
    EditText etName;

    @BindView(R.id.et_person)
    EditText etPerson;

    @BindView(R.id.et_phone)
    EditText etPhone;

    @BindView(R.id.et_addr)
    EditText etDetailAddress;

    @BindView(R.id.tv_category)
    TextView tv_category;

    @BindView(R.id.scrollView)
    DIYScrollView mScrollView;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.ll)
    LinearLayout mLl;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    private String mCityId;
    private String mZoneId;
    private String mCityName;
    private String mZoneName;
    private String mProvinceId;
    private String mCategoryId = "";
    private String mCategoryName = "";
    private String mProvinceName;
    private PopCategory mPopupWindow2;
    private RecyclerView mCategoryRecyclerView;
    private List<CategoryQueryBean> mCategoryDatas = new ArrayList<>();
    private ArrayList<String> mPhotos = new ArrayList<>();
    private CommonAdapter<String> photoAdapter;
    private Button btn_pop_cancle;
    private Button btn_pop_submit;

    @Override
    protected int layoutResId() {
        return R.layout.activity_new_and_update_vendor;
    }

    @Override
    protected void init() {
        if (mPopupWindow2 == null) {
            mPopupWindow2 = new PopCategory(this, R.layout.pop_category_check);
        }
    }

    @Override
    protected void initView() {

        btn_pop_cancle = mPopupWindow2.getView(R.id.btn_cancel);
        btn_pop_submit = mPopupWindow2.getView(R.id.btn_submit);

        mCategoryRecyclerView = mPopupWindow2.getView(R.id.recyclerView);
        mCategoryRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mCategoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mCategoryRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    protected void initData() {
        initDateData();
        getCategoryData();
    }

    @Override
    protected void initListener() {
        super.initListener();


        photoAdapter = new CommonAdapter<String>(this, R.layout.item_photos, mPhotos) {
            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder holder, String s, final int position) {
                ImageView iv = holder.getView(R.id.iv);
                Glide.with(NewVendorActivity.this).load(new File(s)).into(iv);
                CardView cv = holder.getView(R.id.card_view);
                cv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(NewVendorActivity.this)
                                .setTitle("删除对话框")
                                .setMessage("确认不上传该图片？")
                                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                mPhotos.remove(position);
                                                notifyDataSetChanged();
                                                dialog.dismiss();
                                            }
                                        }
                                )
                                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        }
                                )
                                .create()
                                .show();
                    }
                });
            }
        };
        mRecyclerView.setAdapter(photoAdapter);
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("新增供应商");
        mAddress.setText("请添加地址");
    }

    private void beforeSubmit() {

        String mName = etName.getText().toString().trim();
        String mPerson = etPerson.getText().toString().trim();
        String mPhone = etPhone.getText().toString().trim();
        String mDetailAddress = etDetailAddress.getText().toString().trim();

        if (TextUtils.isEmpty(mName)) {
            TsUtils.showToast("请输入商品名称");
            return;
        } else if (TextUtils.isEmpty(mPerson)) {
            TsUtils.showToast("请输入联系人名称");
            return;
        } else if (TextUtils.isEmpty(mPhone) || RexUtils.isMobileNO(mPhone)) {
            TsUtils.showToast("联系人电话格式不正确");
            return;
        } else if (TextUtils.isEmpty(mDetailAddress)) {
            TsUtils.showToast("请填写详细地址");
            return;
        } else if (TextUtils.isEmpty(mCategoryId) || TextUtils.isEmpty(mCategoryName)) {
            TsUtils.showToast("请选择分类");
            return;
        } else if (TextUtils.isEmpty(mProvinceId) || TextUtils.isEmpty(mProvinceName)) {
            mProvinceId = "";
            mProvinceName = "";
        } else if (TextUtils.isEmpty(mCityId) || TextUtils.isEmpty(mCityName)) {
            mCityId = "";
            mCityName = "";
        } else if (TextUtils.isEmpty(mZoneId) || TextUtils.isEmpty(mZoneName)) {
            mZoneId = "";
            mZoneName = "";
        }

        if (mPhotos.size() == 0) {//没有选择图片
            postDataToService(mName, mPerson, mPhone, mCategoryId, mCategoryName, mDetailAddress,
                    mProvinceName, mProvinceId, mCityName, mCityId, mZoneName, mZoneId, "", "")
                    .subscribe(new SubmitResultSubscriber());
        } else {
            postBase64Bitmap(mName, mPerson, mPhone, mDetailAddress);
        }


    }

    private void postBase64Bitmap(final String mName, final String mPerson, final String mPhone, final String mDetailAddress) {

        Observable.just(mPhotos)
                .subscribeOn(Schedulers.io())
                .map(new Function<ArrayList<String>, String[]>() {
                         @Override
                         public String[] apply(@NonNull ArrayList<String> strings) throws Exception {
                             String imgType = "";
                             String[] strArray = new String[strings.size()];
                             for (int i = 0; i < strings.size(); i++) {
                                 if (strings.get(i).endsWith(".jpg")) {
                                     imgType = "jpg";
                                 } else if (strings.get(i).endsWith(".png")) {
                                     imgType = "png";
                                 } else if (strings.get(i).endsWith(".gif")) {
                                     imgType = "gif";
                                 } else {
                                     TsUtils.showToast("请选择png/jpg/gif格式的图片");
                                 }
                                 strArray[i] = BitMapUtil.imgCompress(strings.get(i), 480, 800, 100, imgType);
                             }
                             return strArray;
                         }
                     }
                )
                .map(new Function<String[], String>() {
                         @Override
                         public String apply(@NonNull String[] strings) throws Exception {
                             return JSON.toJSONString(strings);
                         }
                     }
                )
                .flatMap(new Function<String, ObservableSource<ArrayList<ImageBean>>>() {
                             @Override
                             public ObservableSource<ArrayList<ImageBean>> apply(@NonNull String json) throws Exception {
                                 return HttpManager.instance()
                                         .postImg(new ReqImage(json));
                             }
                         }
                )
                .flatMap(new Function<ArrayList<ImageBean>, ObservableSource<GuidBean>>() {
                             @Override
                             public ObservableSource<GuidBean> apply(@NonNull ArrayList<ImageBean> data) throws Exception {
                                 String imgId = "";
                                 String imgFilesName = "";
                                 for (int i = 0; i < data.size(); i++) {
                                     if (i == data.size() - 1) {
                                         imgId = imgId + data.get(i).getId();
                                         imgFilesName = imgFilesName + data.get(i).getUrl();
                                     } else {
                                         imgId = imgId + data.get(i).getId() + ",";
                                         imgFilesName = imgFilesName + data.get(i).getUrl() + ",";
                                     }
                                 }
                                 return postDataToService(mName, mPerson, mPhone, mCategoryId, mCategoryName, mDetailAddress,
                                         mProvinceName, mProvinceId, mCityName, mCityId, mZoneName, mZoneId, imgId, imgFilesName);
                             }
                         }
                )
                .compose(new DialogTransformer<GuidBean>(mProgressBar))
                .subscribe(new SubmitResultSubscriber());
    }


    private Observable<GuidBean> postDataToService(String mName, String mPerson, String mPhone, String mCategoryId, String mCategoryName,
                                                   String mDetailAddress, String mProvinceName, String mProvinceId, String mCityName, String mCityId,
                                                   String mZoneName, String mZoneId, String imgId, String imgfile) {
        return HttpManager.instance()
                .addVendor2(new ReqAddVendorBean(mName, mPerson, mPhone, mCategoryId, mCategoryName,
                        mDetailAddress, mProvinceName, mProvinceId,
                        mCityName, mCityId, mZoneName, mZoneId, imgId, imgfile));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> tempList = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (tempList.size() != 0) {
                    mPhotos.clear();
                    mPhotos.addAll(tempList);
                    photoAdapter.notifyDataSetChanged();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void showCategoryPop(final List<CategoryQueryBean> datas) {

        final CommonAdapter mCategoryItemCateAdapter = new CommonAdapter<CategoryQueryBean>(this, R.layout.pop_selete_category_item, datas) {
            @Override
            protected void convert(ViewHolder holder, final CategoryQueryBean categoryQueryBean, int position) {
                TextView tv_name = holder.getView(R.id.tv_name);
                final CheckBox checkBox = holder.getView(R.id.checkbox);

                tv_name.setText(categoryQueryBean.getName());

                if (categoryQueryBean.isSelete()) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }


                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (categoryQueryBean.isSelete()) {
                            checkBox.setChecked(false);
                            categoryQueryBean.setSelete(false);
                        } else {
                            checkBox.setChecked(true);
                            categoryQueryBean.setSelete(true);
                        }
                    }
                });
            }
        };

        mCategoryRecyclerView.setAdapter(mCategoryItemCateAdapter);

        btn_pop_cancle.setOnClickListener(new View.OnClickListener() {//点击取消操作
            @Override
            public void onClick(View v) {
                mPopupWindow2.dismiss();
            }
        });

        btn_pop_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mCategoryId = "";
                mCategoryName = "";

                Observable
                        .just(datas)
                        .map(new Function<List<CategoryQueryBean>, List<CategoryQueryBean>>() {
                                 @Override
                                 public List<CategoryQueryBean> apply(@NonNull List<CategoryQueryBean> categoryQueryBeen) throws Exception {
                                     return parseCategory1(categoryQueryBeen);
                                 }
                             }
                        ).map(new Function<List<CategoryQueryBean>, String>() {
                                  @Override
                                  public String apply(@NonNull List<CategoryQueryBean> categoryQueryBeen) throws Exception {
                                      return parseCategory2(categoryQueryBeen);
                                  }
                              }
                ).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ErrorHandleSubscriber<String>() {
                                       @Override
                                       public void onNext(@NonNull String s) {
                                           tv_category.setText(s);
                                       }
                                   }
                        );


                mPopupWindow2.dismiss();

                tv_category.setText(mCategoryName);
            }
        });


        mPopupWindow2.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }

    private String parseCategory2(List<CategoryQueryBean> categoryQueryBeen) {

        String strId = "";
        String strName = "";

        for (int i = 0; i < categoryQueryBeen.size(); i++) {

            CategoryQueryBean bean = categoryQueryBeen.get(i);

            if (i == categoryQueryBeen.size() - 1) {
                strId = strId + bean.getId();
                strName = strName + bean.getName();
            } else {
                strId = strId + bean.getId() + ",";
                strName = strName + bean.getName() + ",";
            }
        }

        mCategoryId = strId;
        mCategoryName = strName;
        return mCategoryName;
    }

    private List<CategoryQueryBean> parseCategory1(List<CategoryQueryBean> categoryQueryBeen) {

        List<CategoryQueryBean> data = new ArrayList<>();
        data.clear();

        for (int i = 0; i < categoryQueryBeen.size(); i++) {
            CategoryQueryBean bean = categoryQueryBeen.get(i);
            if (bean.isSelete()) {
                data.add(bean);
            }
        }
        return data;
    }

    private void getCategoryData() {
        HttpManager.instance()
                .getCategoryQuery2(new ReqQueryCategory())
                .map(new Function<ArrayList<CategoryQueryBean>, List<CategoryQueryBean>>() {
                         @Override
                         public List<CategoryQueryBean> apply(@NonNull ArrayList<CategoryQueryBean> categoryQueryBeen) throws Exception {
                             return parseCategory(categoryQueryBeen);
                         }
                     }
                ).subscribe(new ErrorHandleSubscriber<List<CategoryQueryBean>>() {
                                @Override
                                public void onNext(@NonNull List<CategoryQueryBean> categoryQueryBeen) {
                                    mCategoryDatas.addAll(categoryQueryBeen);
                                }
                            }
        );
    }

    private List<CategoryQueryBean> parseCategory(ArrayList<CategoryQueryBean> categoryQueryBeen) {

        List<CategoryQueryBean> data = new ArrayList<>();

        for (int i = 0; i < categoryQueryBeen.size(); i++) {
            CategoryQueryBean bean = categoryQueryBeen.get(i);
            if (bean.getFid().equals("0")) {
                data.add(bean);//为一级类
            }
        }
        return data;
    }


    public ArrayList<IPickerAddressBean> parseData(String result) {//Gson 解析
        ArrayList<IPickerAddressBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                IPickerAddressBean entity = gson.fromJson(data.optJSONObject(i).toString(), IPickerAddressBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    @OnClick({R.id.btn_submit, R.id.tv_address, R.id.tv_category, R.id.btn_select_pic})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                beforeSubmit();
                break;
            case R.id.tv_address:
                showAddress();
                break;
            case R.id.tv_category:
                if (mCategoryDatas.size() == 0) {
                    TsUtils.showToast("请先添加商品分类");
                    return;
                }
                showCategoryPop(mCategoryDatas);
                break;
            case R.id.btn_select_pic:
                getPickPhoto();
                break;
            default:
                break;
        }
    }

    private void getPickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(2)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(true)
                .start(this, PhotoPicker.REQUEST_CODE);
    }


    private void showAddress() {

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                mProvinceName = options1Items.get(options1).getPickerViewText();
                mProvinceId = String.valueOf(options1Items.get(options1).getId());

                mCityName = options2Items.get(options1).get(options2).getPickerViewText();
                mCityId = String.valueOf(options2Items.get(options1).get(options2).getCode());

                mZoneName = options3Items.get(options1).get(options2).get(options3).getPickerViewText();
                mZoneId = String.valueOf(options3Items.get(options1).get(options2).get(options3).getCode());

                mAddress.setText(options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2).getPickerViewText() + "-" +
                        options3Items.get(options1).get(options2).get(options3).getPickerViewText());

            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }

    private ArrayList<IPickerAddressBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<IPickerAddressBean.CityBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<IPickerAddressBean.CityBean.ZoneBean>>> options3Items = new ArrayList<>();

    private void initDateData() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                /**
                 * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
                 * 关键逻辑在于循环体
                 *
                 * */
                String JsonData = new GetJsonDataUtil().getJson(NewVendorActivity.this, "province.json");//获取assets目录下的json文件数据

                ArrayList<IPickerAddressBean> jsonBean = parseData(JsonData);//用Gson 转成实体

                /**
                 * 添加省份数据
                 * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
                 * PickerView会通过getPickerViewText方法获取字符串显示出来。
                 */
                options1Items = jsonBean;

                for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
                    ArrayList<IPickerAddressBean.CityBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
                    ArrayList<ArrayList<IPickerAddressBean.CityBean.ZoneBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

                    for (int c = 0; c < jsonBean.get(i).getCity().size(); c++) {//遍历该省份的所有城市
                        IPickerAddressBean.CityBean cityBean = jsonBean.get(i).getCity().get(c);
                        CityList.add(cityBean);//添加城市

                        ArrayList<IPickerAddressBean.CityBean.ZoneBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                        //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                        if (jsonBean.get(i).getCity().get(c).getZone() == null
                                || jsonBean.get(i).getCity().get(c).getZone().size() == 0) {
                            City_AreaList.add(new IPickerAddressBean.CityBean.ZoneBean());
                        } else {
                            for (int d = 0; d < jsonBean.get(i).getCity().get(c).getZone().size(); d++) {//该城市对应地区所有数据
                                IPickerAddressBean.CityBean.ZoneBean AreaName = jsonBean.get(i).getCity().get(c).getZone().get(d);

                                City_AreaList.add(AreaName);//添加该城市所有地区数据
                            }
                        }
                        Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                    }
                    /**
                     * 添加城市数据
                     */
                    options2Items.add(CityList);
                    /**
                     * 添加地区数据
                     */
                    options3Items.add(Province_AreaList);

                }
            }
        }.start();
    }


}

